"""DBM database based on dbhash with built-in file locks
so that only one person can read or modify the data at once.


"""

# Imports
import os
import sys
import dbhash

import lock

_open=open
# Lock DBM
class DBM(object):
	'''
	provide interface to persist dictionary data into dbhash file
	'''
	def __init__(self, file, mode, warn):
		if '.' in file:
			raise NameError("Database names should not contain '.' characters.")
		self.locks = lock.Lock(expire=2, timeout=10, warn=warn)
		self.locks.lock(file)
		self.cache = dbhash.open(file, 'c', mode)
        
    def __getitem__(self, name):
        for file in self.locks.files.keys():
            if not self.locks.isLocked(file):
                raise lock.LockError('Lock no longer valid.')
        else:
           return self.cache[name]

    def __setitem__(self, name, value):
        for file in self.locks.files.keys():
            if not self.locks.isLocked(file):
                raise lock.LockError('Lock no longer valid.')
        else:
           return self.cache[name]= value
           
    def commit(self):
        for file in self.locks.files.keys():
            self.locks.commit(file)
            
    def rollback(self):
        for file in self.locks.files.keys():
            self.locks.rollback(file)
            
    def close(self,commit=False):
        res = self.cache.close()
        if commit:
            self.commit()
        else:
            self.rollback()
        self.locks.__del__()

    def __del__(self):
        self.rollback()
        
    def sync(self):
        self.cache.sync()
        
def open(file, flag=None, mode=None, warn=False):
	if not os.path.exists(file):
		if mode == None:
			mode = 0666
		fp = dbhash(file, 'w', mode)
		fp.close()
    if mode == None:
        mode = 0666
    return Database(file, mode, warn)